package com.example.app1

import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import kotlin.math.cos
import kotlin.math.sin

class PieDrawable(private val colors: Array<Int>, private val percent: Array<Float>): Drawable() {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    override fun draw(canvas: Canvas) {
        var startAngle = 0f
        colors.forEachIndexed { index, color ->
            paint.color = color
            val sweep = percent[index] * 360
            if (index == highLight) {
                val angle = (sweep / 2) + startAngle.toDouble()
                val dx = cos(Math.toRadians(angle)) * dis * offsetFraction
                val dy = sin(Math.toRadians(angle)) * dis * offsetFraction
                // translation也行
                canvas.drawArc(
                    width / 2f - radius + dx.toFloat(),
                    height / 2f - radius + dy.toFloat(),
                    width / 2f + radius + dx.toFloat(),
                    height / 2f + radius + dy.toFloat(),
                    startAngle,
                    sweep,
                    true,
                    paint
                )
            } else {
                canvas.drawArc(
                    width / 2f - radius,
                    height / 2f - radius,
                    width / 2f + radius,
                    height / 2f + radius,
                    startAngle,
                    sweep,
                    true,
                    paint
                )
            }
            startAngle += sweep
        }
    }

    override fun setAlpha(alpha: Int) {
        paint.alpha = alpha
    }

    override fun getAlpha(): Int {
        return paint.alpha
    }

    override fun setColorFilter(colorFilter: ColorFilter?) {
        paint.colorFilter = colorFilter
    }

    override fun getColorFilter(): ColorFilter? {
        return paint.colorFilter
    }

    override fun getOpacity(): Int {
      return PixelFormat.OPAQUE
    }
}